#include <iostream>
#include <typeinfo>

class Any
{
public:
    Any()
        :_content(nullptr)
    {}

    ~Any()
    {
        delete _content;
    }

    template<class T>
    Any(const T &val)
        :_content(new placeholder<T>(val))
    {}

    Any(const Any &other)
        :_content(other._content ? other._content->clone() : nullptr)
    {}

    void swap(Any &other)
    {
        std::swap(_content, other._content);
    }

    template<class T>
    Any &operator=(const T &val)
    {
        Any tmp(val);
        swap(tmp);
        return *this;
    }

    Any &operator=(Any other)
    {
        swap(other);
        return *this;
    }

    template<class T>
    T *get()
    {
        if(typeid(T) != _content->type())       // 获取数据的类型必须与保存的一致
            return nullptr;
        return &(((placeholder<T> *)_content)->_val);
    }

private:
    class holder
    {
    public:
        virtual ~holder() {};
        virtual const std::type_info& type() = 0;
        virtual holder *clone() = 0;
    };

    template<class T>
    class placeholder : public holder
    {
    public:
        placeholder(const T& val)
            :_val(val)
        {}

        virtual ~placeholder()
        {}

        virtual const std::type_info& type()
        {
            return typeid(T);
        }

        virtual holder *clone()
        {
            return (new placeholder<T>(_val));
        }

        T _val;
    };

    holder *_content;
};